#include <iostream>
#include <unistd.h>
#include <cstdio>
#include <pthread.h>
#include <string>
#include <cstring>
#include <vector>

using namespace std;

#define NUM 3

//加上__thread就是线程局部存储
//__thread是编译选项
//只能修饰内置类型
__thread int share = 10;

class threadInfo
{
public:
    threadInfo(const string &name)
        : _name(name)
    {
    }

public:
    string _name;
};

string toHex(pthread_t tid)
{
    char buffer[64] = {0};
    snprintf(buffer, sizeof(buffer), "%p", tid);
    return buffer;
}

void *threadRoutine(void *args)
{
    // int test_i = 0;
    threadInfo *ti = static_cast<threadInfo *>(args);
    for (int i = 0; i < NUM; i++)
    {
        printf("%s, tid : %s, pid : %d, share = %d, &share = %p\n", ti->_name.c_str(), toHex(pthread_self()).c_str(), getpid(), share, &share);
        // cout << ti->_name << ", tid : " << toHex(pthread_self()) << ", pid : " << getpid() << endl;
        //  cout << ti->_name << ", tid : " << toHex(pthread_self()) << ", pid : " << getpid()
        //          << ", test_i =  " << test_i << ", &test_i = " << &test_i << endl;
        // test_i++;
        share++;
        sleep(1);
    }

    delete ti;
    return nullptr;
}

int main()
{
    std::vector<pthread_t> tids; // 用于存放线程ID
    // 创建多线程
    for (int i = 0; i < NUM; i++)
    {
        pthread_t tid = 0;
        // std::cout << to_string(i) << std::endl;
        std::string name = "thread" + to_string(i);
        // std::cout << name << std::endl;

        threadInfo *ti = new threadInfo(name);
        pthread_create(&tid, nullptr, threadRoutine, ti);
        tids.push_back(tid);
        sleep(1);
    }

    // 线程等待
    for (int i = 0; i < NUM; i++)
    {
        pthread_join(tids[i], nullptr);
    }

    return 0;
}